package com.djsearch.ui;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.bean.LoginSuccess;
import com.djsearch.bean.LvYouRequestParmeterBaseBean;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.DefaultController;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.data.LvYouDataRequest;
import com.djsearch.data.OperateSQLiteDataBase;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 登陆页面
 * 
 * @author yinxing
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	private static final String APP_ID = "222222";
	private static final String SCOPE = "all";
    private Tencent mTencent;
	TextView login;
	TextView register;
//	TextView loginByQQ;
//	TextView loginByWeibo;
	private EditText nameEdit,passWordEdit;//用户名编辑框，密码编辑框
	private OperateSQLiteDataBase operateSQLiteDataBase;
	private CheckBox ischeckmima,ischecklogin;//记住密码，自动登录
	private Button btnBack;
	private Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.login_layout);
		mTencent = Tencent.createInstance(APP_ID, this);
		initPages();
		initHandler();
		initOnClick();
	}

	private void initPages(){
		btnBack = (Button)findViewById(R.id.btnBack);
		login=(TextView)findViewById(R.id.login);
		register=(TextView)findViewById(R.id.onestepregister);
//		loginByQQ=(TextView)findViewById(R.id.loginbyqq);
//		loginByWeibo=(TextView)findViewById(R.id.loginbyweibo);
		login.setOnClickListener(this);
		register.setOnClickListener(this);
//		loginByQQ.setOnClickListener(this);
//		loginByWeibo.setOnClickListener(this);
		ischeckmima = (CheckBox)findViewById(R.id.ischeckmima);
		ischecklogin = (CheckBox)findViewById(R.id.ischecklogin);
		nameEdit = (EditText)findViewById(R.id.init_name);
		passWordEdit = (EditText)findViewById(R.id.init_password);
		if (preferences.getBoolean("isMiMaChecked", false)) {
			ischeckmima.setChecked(true);
			ischeckmima.setButtonDrawable(R.drawable.checkbox_selected);
			nameEdit.setText(preferences.getString("userId", ""));
		    passWordEdit.setText(preferences.getString("userPassWord", ""));
		}
		if (preferences.getBoolean("isLoginChecked", false)) {
			ischecklogin.setChecked(true);
			ischecklogin.setButtonDrawable(R.drawable.checkbox_selected);
			
		}
	}
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
//		Intent intent;
		switch (v.getId()) {
		case R.id.onestepregister:
			startActivity(LoginActivity.this,RegisterActivity.class,0);
			break;
//		case R.id.loginbyqq:
//             onClickLoginByQQ();
//			break;
//		case R.id.loginbyweibo:
//			break;
		default:
			break;
		}
	}
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	       mTencent.onActivityResult(requestCode, resultCode, data) ;
	 }
	private void onClickLoginByQQ() {
        if (!mTencent.isSessionValid()) {
            IUiListener listener = new BaseUiListener() {
                @Override
                protected void doComplete(JSONObject values) {
                    Log.i("LOGIN", values.toString());
                }
            };
            mTencent.login(this, SCOPE, listener);
        } 
    }
	 private class BaseUiListener implements IUiListener {

	        @Override
	        public void onComplete(JSONObject response) {
	            doComplete(response);
	        }

	        protected void doComplete(JSONObject values) {

	        }

	        @Override
	        public void onError(UiError e) {
	        }

	        @Override
	        public void onCancel() {
	        }
	    }
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
				startActivity(LoginActivity.this, MainActivity.class, 1);
			    mTencent.logout(this);
		}
		return false;
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				// 取数据
				case 0:
					missDialog();
					if (LvYouDataRequest.getIntence().getStatus().equals("0")) {
						Toast.makeText(LoginActivity.this, "登录成功", 5000).show();
						SharedPreferences.Editor editor = preferences.edit();
						editor.putString("userId", nameEdit.getText().toString()).commit();
						editor.putString("userPassWord", passWordEdit.getText().toString()).commit();
						editor.putBoolean("isLogined", true).commit();
						startActivity(LoginActivity.this, MainActivity.class, 1);
					} else if (LvYouDataRequest.getIntence().getStatus().equals("1")) {
						Toast.makeText(LoginActivity.this, "账号不存在", 5000).show();
					} else if (LvYouDataRequest.getIntence().getStatus().equals("2")) {
						Toast.makeText(LoginActivity.this, "密码有误", 5000).show();
					}
					break;
				default:
					break;
				}
			}
			
		};
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(LoginActivity.this, null, 1);
			}
		});
		login.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				saveInfo();
			}
		});
		ischecklogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ischecklogin.isChecked()) {
					ischecklogin.setButtonDrawable(R.drawable.checkbox_selected);
				} else {
					ischecklogin.setButtonDrawable(R.drawable.checkbox_normal);
				}
			}
		});
		ischeckmima.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ischeckmima.isChecked()) {
					ischeckmima.setButtonDrawable(R.drawable.checkbox_selected);
				} else {
					ischeckmima.setButtonDrawable(R.drawable.checkbox_normal);
				}
			}
		});
	}

	private  void saveInfo() {
		
		if (nameEdit.getText().toString().equals("")) {
			startAnimation(nameEdit);
		} else if (passWordEdit.getText().toString().equals("")) {
			startAnimation(passWordEdit);
		} else {
			SharedPreferences.Editor editor = preferences.edit();
			if (ischecklogin.isChecked()) {
				//自动登录
				editor.putBoolean("isLoginChecked", true).commit();
			} else {
				editor.putBoolean("isLoginChecked", false).commit();
			}
			if (ischeckmima.isChecked()) {
				//记住密码
				ischeckmima.setButtonDrawable(R.drawable.checkbox_selected);
				editor.putBoolean("isMiMaChecked", true).commit();
			} else {
				editor.putBoolean("isMiMaChecked", false).commit();
			}
			LoginBean loginBean = new LoginBean();
			loginBean.setUserName(nameEdit.getText().toString());
			loginBean.setPassWord(passWordEdit.getText().toString());
			loginRequest(loginBean);
		}
	}

	private void loginRequest(final LoginBean loginBean) {
		showDialog("正在登录...");
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
					int isOk = LvYouDataRequest.getIntence().requestWcf("Login",loginBean);
//					if (isOk == 0)
					handler.sendEmptyMessage(0);

			}
		}).start();
	}
	
	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		LoginSuccess loginSuccess = new LoginSuccess();
		SharedPreferences.Editor editor = preferences.edit();
		try {
			editor.putString("tuijianren", response.getString("recommendPerson")).commit();
			editor.putString("jiangjinQuan", response.getString("jiangjinMoney")).commit();
			editor.putString("daiJinQuan", response.getString("voucherMoney")).commit();
			editor.putString("xianJinMoney", response.getString("xianjiinMoney")).commit();
			editor.putString("userId", response.getString("userId")).commit();
			editor.putString("userPassWord", passWordEdit.getText().toString()).commit();
			editor.putBoolean("isLogined", true).commit();
			startActivity(LoginActivity.this, MainActivity.class, 1);
			
//			loginSuccess.setUserId(response.getString("userId"));
//			loginSuccess.setRecommendPerson(response.getString("recommendPerson"));
//			loginSuccess.setJiangjinMoney(response.getString("jiangjinMoney"));
//			loginSuccess.setVoucherMoney(response.getString("voucherMoney"));
//			loginSuccess.setXianjinMoney(response.getString("xianjiinMoney"));
//			if (operateSQLiteDataBase == null) {
//				operateSQLiteDataBase = OperateSQLiteDataBase
//						.getOperateSQLiteDataBase(this);
//			}
//			operateSQLiteDataBase.inputMyInfoToTable(loginSuccess,"my_info_table",this);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			editor.putBoolean("isLogined", false);
		} finally {
			/*if (operateSQLiteDataBase != null) {
				operateSQLiteDataBase.closeDataBase(sqLiteDatabase)
			}*/
		}
		
	}

	
	
	public class LoginBean extends LvYouRequestParmeterBaseBean{
		private String userName;
		private String passWord;
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public String getPassWord() {
			return passWord;
		}
		public void setPassWord(String passWord) {
			this.passWord = passWord;
		}
	}
	
	
	
	
	private String Md5(String passWord) { 
		try { 
			MessageDigest md = MessageDigest.getInstance("MD5"); 
		    md.update(passWord.getBytes()); 
		    byte b[] = md.digest(); 
		    int i; 
		    StringBuffer buf = new StringBuffer(""); 
		    for (int offset = 0; offset < b.length; offset++) { 
			i = b[offset]; 
			if (i<0){
				i += 256; 
			}
			if(i<16){
				buf.append("0"); 
			}
			buf.append(Integer.toHexString(i)); 
			} 
		    return getMD5PassWord(buf.toString());
		}
		catch (NoSuchAlgorithmException e) { 
			// TODO Auto-generated catch block e.printStackTrace(); } } 
		}
		return passWord;
	}

	
	/**
	 * 将加密后的md5密码中小写字母转换为大写字母
	 * @param passWord
	 * @return
	 */
	private String getMD5PassWord (String passWord) {
		char letters[] = new char[passWord.length()];  
		for(int i=0;i<passWord.length();i++){      
			char letter = passWord.charAt(i);   
		if(letter>='a' && letter<='z')    
			letter = (char) (letter-32);   
		letters[i] = letter;  }    
		String resultPsd =  new String(letters);
		return resultPsd;
	}
	
	
	
}
